package com.yhy.auth.config;

import com.yhy.auth.extension.sms.SmsCodeAuthenticationProvider;
import com.yhy.auth.extension.wechat.WechatAuthenticationProvider;
import com.yhy.common.security.config.PermitAllProperties;
import com.yhy.common.security.service.MyUserDetailsService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author jax-li
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    final PermitAllProperties permitAllProperties;
    final MyUserDetailsService userDetailsService;

    @Override
    @SneakyThrows
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {
        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .and()
                .authenticationProvider(smsCodeAuthenticationProvider())
                .authenticationProvider(wechatAuthenticationProvider())
        ;
    }

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }

    /**
     * 允许匿名访问接口 主要是 oauth 接口
     *
     * @param http http
     */
    @Override
    @SneakyThrows
    protected void configure(HttpSecurity http) {
        http.authorizeRequests()
                .antMatchers(permitAllProperties.getUrls().toArray(new String[0]))
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .ignoringAntMatchers(permitAllProperties.getUrls().toArray(new String[0]))
        ;
    }

    /**
     * 手机验证码认证授权提供者
     */
    @Bean
    public SmsCodeAuthenticationProvider smsCodeAuthenticationProvider() {
        return new SmsCodeAuthenticationProvider(userDetailsService);
    }

    /**
     * 微信认证授权提供者
     */
    @Bean
    public AuthenticationProvider wechatAuthenticationProvider() {
        return new WechatAuthenticationProvider(userDetailsService);
    }

}